<?php

// 代付查询通知控制器

namespace app\api\controller;

use app\api\controller\Base;
use think\facade\Cache;
use think\facade\Log;
use think\Db;

class PaidQuery extends Base
{

    /**
     * 代付查询通知
     */
    public function query()
    {
        try {
            // 只允许命令行访问
            if (PHP_SAPI != 'cli') {
                return ['code' => 999, 'msg' => '404'];
            }

            // 银行卡代付处理
            $this->cardPaid();
            // 支付宝代付处理
            $this->alipayPaid();
        } catch (\Exception $e) {
            payment_error_log(770000, $e->getMessage());
            return ['code' => 999, 'msg' => '404'];
        }
    }

    /**
     * 银行卡代付处理 
     * @access protected
     * @return mixed
     */
    protected function cardPaid()
    {

        // 设置至少间隔多少秒处理一次
        $notice_time = 15;

        // 代付公司配置
        $all_child_company = Db::name('payment_paid_company')
            ->where([])
            ->column('*', 'name');

        Db::name('payment_order_paid')
            ->where('status', '=', 1)
            ->chunk(10, function ($all) use ($notice_time, $all_child_company) {
                foreach ($all as $single) {

                    // 处理规则
                    if ($single['update_time'] + $notice_time < time()) {
                        sleep(1);
                        $redis = Cache::store('redis');

                        // 可能会在一秒中多次通知相同订单，用redis处理。
                        $order_notify_key = 'order_notify_' . $single['order_id'];
                        $order_notify = $redis->has($order_notify_key);
                        if ($order_notify) {
                            //payment_error_log(770001, $single, '多次通知:在一秒中多次通知相同订单');
                            unset($single);
                            continue;
                        } else {
                            $redis->set($order_notify_key, 1, 5);
                        }

                        // 订单状态
                        if (isset($order_status)) {
                            unset($order_status);
                        }

                        if (!isset($all_child_company[$single['child_company']])) {
                            payment_error_log(770002, $single);
                            continue;
                        }
                        $child_company_config = $all_child_company[$single['child_company']];
                        // 代付公司关闭定时自动查询
                        if ($child_company_config['auto_query'] == 0) {
                            continue;
                        }

                        $payment_company = $single['company'] . 'PaidQuery';
                        $order_id = $single['order_id'];
                        if (in_array($single['company'], ['abcdefg'])) {
                            $order_id = $single['other_order_id'];
                        }

                        // 实例化银行卡代付订单模型
                        $card_paid_obj = new \app\api\model\PaymentOrderPaid();
                        $resdata = $card_paid_obj->$payment_company($order_id, $child_company_config, $single, false, true);

                        $return_param = $resdata['return_param'];
                        $resarray = json_decode($return_param, true);

                        // 游易付代付
                        if ($single['company'] == 'youyifu') {
                            if (isset($resarray['state'])) {
                                // 成功
                                if ($resarray['state'] == 1) {
                                    $order_status = 2;
                                }
                                // 失败
                                if ($resarray['state'] == 2) {
                                    $order_status = 3;
                                }
                            }
                        }
                        // 薪航向代付
                        if ($single['company'] == 'xhx') {
                            if (isset($resarray['queryItems'][0]['orderStatus'])) {
                                // 成功
                                if ($resarray['queryItems'][0]['orderStatus'] == 2) {
                                    $order_status = 2;
                                }
                                // 失败
                                if ($resarray['queryItems'][0]['orderStatus'] == 3) {
                                    $order_status = 3;
                                }
                            }
                        }
                        // 灵时云代付
                        if ($single['company'] == 'lsy') {
                            if (isset($resarray['data']['planDetail'][0]['payState'])) {
                                // 成功
                                if ($resarray['data']['planDetail'][0]['payState'] == 3) {
                                    $order_status = 2;
                                }
                                // 失败
                                if ($resarray['data']['planDetail'][0]['payState'] == 4) {
                                    $order_status = 3;
                                }
                            }
                        }
                        // 付易通代付
                        if ($single['company'] == 'fuyitong') {
                            if (isset($resarray['status'])) {
                                // 成功
                                if ($resarray['status'] == 300) {
                                    $order_status = 2;
                                }
                                // 失败
                                if ($resarray['status'] == 306) {
                                    $order_status = 3;
                                }
                            }
                        }
                        // 大栋代付
                        if ($single['company'] == 'dadong') {

                            if (isset($resarray['code']) && $resarray['code'] == 'E2101') {
                                if ($single['other_order_id'] == '102') {
                                    // 重新提交
                                    $this->cardPaidFailHandle($single, $child_company_config);
                                    continue;
                                }
                            }

                            if (isset($resarray['biz']['orderStatus'])) {
                                // 成功
                                if ($resarray['biz']['orderStatus'] == 'Success') {
                                    $order_status = 2;
                                }
                                // 失败
                                if ($resarray['biz']['orderStatus'] == 'Fail') {
                                    $order_status = 3;
                                }
                            }
                        }
                        // 招商代付
                        if ($single['company'] == 'zhaoshang') {
                            if (isset($resarray['NTSTLLSTZ']['RTNFLG'])) {
                                // 成功
                                if ($resarray['NTSTLLSTZ']['RTNFLG'] == 'S') {
                                    $order_status = 2;
                                }
                                // 失败
                                if (in_array($resarray['NTSTLLSTZ']['RTNFLG'], ['F', 'B'])) {
                                    $order_status = 3;
                                }
                            }
                        }
                        // 银联代付
                        if ($single['company'] == 'chinapay') {
                            sleep(30);
                            if (isset($resarray['stat'])) {
                                // 成功
                                if ($resarray['stat'] == 's') {
                                    $order_status = 2;
                                }
                                // 失败
                                if (in_array($resarray['stat'], ['6', '9'])) {
                                    $order_status = 3;
                                }
                            }
                        }
                        // 杉德代付
                        if ($single['company'] == 'sandpay') {
                            if (isset($resarray['resultFlag'])) {
                                // 成功
                                if ($resarray['resultFlag'] == '0') {
                                    $order_status = 2;
                                }
                                // 失败
                                if ($resarray['resultFlag'] == '1') {
                                    $order_status = 3;
                                }
                            }
                        }
                        // 信汇代付
                        if ($single['company'] == 'xinhui') {
                            if (isset($resarray['rtnCode']) && $resarray['rtnCode'] == '0000') {
                                if (isset($resarray['oriRtnCode'])) {
                                    // 成功
                                    if ($resarray['oriRtnCode'] == '0000') {
                                        $order_status = 2;
                                    }
                                    // 失败
                                    if (in_array($resarray['oriRtnCode'], ['0001', '0006', '0007', '0008', '0010', '0013'])) {
                                        $order_status = 3;
                                    }
                                }
                            }
                        }
                        // 连连代付
                        if ($single['company'] == 'lianlian') {

                            if (isset($resarray['result_pay']) && $resarray['result_pay'] == 'CHECK') {
                                $order_return_param = $single['return_param'];
                                $order_return_param_array = json_decode($order_return_param, true);

                                if (isset($order_return_param_array['confirm_code'])) {
                                    // 重新提交
                                    $this->cardPaidFailHandle($single, $child_company_config);
                                    continue;
                                }
                            }

                            if (isset($resarray['result_pay'])) {
                                // 成功
                                if ($resarray['result_pay'] == 'SUCCESS') {
                                    $order_status = 2;
                                }
                                // 失败
                                if ($resarray['result_pay'] == 'FAILURE') {
                                    $order_status = 3;
                                }
                                // 失败
                                if ($resarray['result_pay'] == 'CLOSED') {
                                    $order_status = 3;
                                }
                            }
                        }
                        // 银商分账代付
                        if ($single['company'] == 'ysfz') {
                            if (isset($resarray['data']['status'])) {
                                // 成功
                                if ($resarray['data']['status'] == 2) {
                                    $order_status = 2;
                                }
                                // 失败
                                if ($resarray['data']['status'] == 3) {
                                    $order_status = 3;
                                }
                            }
                        }

                        if (isset($order_status)) {

                            try {
                                $update_data = Db::name('payment_order_paid')
                                    ->where(['order_id' => $single['order_id'], 'status' => 1])
                                    ->update(['status' => $order_status, 'update_time' => time()]);
                            } catch (\Exception $e) {
                                payment_error_log(770003, $single, $e->getMessage());
                                continue;
                            }

                            // 更新代付订单表状态失败
                            if (!$update_data) {
                                payment_error_log(770004, $single);
                                continue;
                            }

                            // 失败：代付金额退回
                            if ($order_status == 3) {
                                // 代付绿色通道
                                if ($single['paid_green_channel_status'] == 0) {
                                    try {
                                        Db::name('payment_cash')
                                            ->where(['merchant_id' => $single['merchant_id']])
                                            ->inc('paid_cash', $single['deduct_cash'])
                                            ->dec('paid_sum_cash', $single['deduct_cash'])
                                            ->dec('paid_count', 1)
                                            ->update(['update_time' => time()]);
                                    } catch (\Exception $e) {
                                        payment_error_log(770005, $single, $e->getMessage());
                                    }
                                }
                            }
                            // 成功：处理商户等配置
                            if ($order_status == 2) {

                                // 指定代付公司不执行
                                if (!in_array($single['company'], ['zfb'])) {

                                    $paid_cash = $single['cash'];
                                    $expire = strtotime(date('Y-m-d', strtotime('+1 day'))) - time();

                                    // 更新商户号今天已经代付的金额总数
                                    $merchant_day_paid_cash_sum = $single['merchant_id'] . '_day_paid_cash_sum';
                                    $now_merchant_day_paid_cash_sum = $redis->has($merchant_day_paid_cash_sum);
                                    if ($now_merchant_day_paid_cash_sum) {
                                        $redis->inc($merchant_day_paid_cash_sum, $paid_cash);
                                    } else {
                                        $redis->set($merchant_day_paid_cash_sum, $paid_cash, $expire);
                                    }

                                    // 更新代付公司中的子商户号今天已经代付的金额总数
                                    $children_day_paid_cash_sum = $single['child_company'] . '_day_paid_cash_sum';
                                    $now_children_day_paid_cash_sum = $redis->has($children_day_paid_cash_sum);
                                    if ($now_children_day_paid_cash_sum) {
                                        $redis->inc($children_day_paid_cash_sum, $paid_cash);
                                    } else {
                                        $redis->set($children_day_paid_cash_sum, $paid_cash, $expire);
                                    }

                                    // 通道每天最多代付成功次数
                                    $children_company_success_count = $single['child_company'] . '_success_count';
                                    $now_children_company_success_count = $redis->has($children_company_success_count);
                                    if ($now_children_company_success_count) {
                                        $redis->inc($children_company_success_count, 1);
                                    } else {
                                        $redis->set($children_company_success_count, 1, $expire);
                                    }

                                    // 通道每天最多代付用户成功次数（银行卡）
                                    if ($child_company_config['user_success_count'] != '0') {
                                        $children_company_user_success_count = $single['child_company'] . '_user_' . $single['bank_card'];
                                        $now_children_company_user_success_count = $redis->has($children_company_user_success_count);
                                        if ($now_children_company_user_success_count) {
                                            $redis->inc($children_company_user_success_count, 1);
                                        } else {
                                            $redis->set($children_company_user_success_count, 1, $expire);
                                        }
                                    }
                                }
                            }

                            // 把代付信息通知给商户
                            $merchant_create_param = json_decode($single['create_param'], true);
                            // 商户开启通知
                            if ($merchant_create_param['notify_open'] == 1) {
                                $notify_url = $merchant_create_param['notify_url'];
                                $notify_data['code'] = 10000;                                         // 成功状态码
                                $notify_data['merchant_id'] = $single['merchant_id'];                 // 商户号
                                $notify_data['merchant_order_id'] = $single['merchant_order_id'];     // 商户订单号
                                $notify_data['order_id'] = $single['order_id'];                       // 平台订单号
                                $notify_data['app_id'] = $single['app_id'];                           // 应用id
                                $notify_data['cash'] = $single['cash'] / 100;                         // 代付现金    
                                $notify_data['deduct_cash'] = $single['deduct_cash'] / 100;           // 扣除金额    
                                $notify_data['mode'] = $single['mode'];                               // 代付方法：0自动，1手动
                                $notify_data['trade_type'] = $single['trade_type'];                   // 交易类型：比如充值、代付                                  
                                $notify_data['body'] = $single['body'];                               // 代付说明
                                $notify_data['time'] = time();                                        // 更新时间
                                $notify_data['extra'] = $merchant_create_param['extra'];              // 商户自定义备注
                                // 订单状态：1:处理中 2:成功 3:失败 4:异常
                                $notify_data['status'] = $order_status;
                                $notify_data['sign'] = md5('merchant_id=' . $notify_data['merchant_id'] . '&merchant_order_id=' . $notify_data['merchant_order_id'] . '&order_id=' . $notify_data['order_id'] . '&cash=' . $notify_data['cash'] . '&status=' . $notify_data['status'] . '&time=' . $notify_data['time'] . '&key=' . $merchant_create_param['key']);

                                $resdata = go_curl($notify_url, $notify_data, 'get', 12);
                                if (stripos($resdata, 'success') === false) {
                                    // 通知失败,准备多次通知
                                    $url_param = http_build_query($notify_data);
                                    $url = strpos($notify_url, '?') !== false ? $notify_url . '&' . $url_param : $notify_url . '?' . $url_param;

                                    $notify_array = [
                                        'order_id' => $single['order_id'],
                                        'merchant_id' => $single['merchant_id'],
                                        'merchant_order_id' => $single['merchant_order_id'],
                                        'other_order_id' => $single['other_order_id'],
                                        'app_id' => $single['app_id'],
                                        'cash' => $single['cash'],
                                        'type' => 0,
                                        'trade_type' => $single['trade_type'],
                                        'status' => 0,
                                        'manual' => 0,
                                        'count' => 0,
                                        'create_time' => $single['create_time'],
                                        'update_time' => time(),
                                        'url' => $url,
                                        'remark' => substr($resdata, 0, 60000),
                                    ];
                                    // 插入多次通知数据库
                                    try {
                                        Db::name('payment_order_notify')->insert($notify_array);
                                    } catch (\Exception $e) {
                                        payment_error_log(770006, $notify_array, $e->getMessage());
                                    }

                                    Log::record("代付通知商户号{$single['merchant_id']}失败记录：" . $single['order_id'] . '——' . '0', 'log');
                                    Log::record('代付通知URL参数：' . $url, 'log');
                                    Log::record('代付通知返回内容：' . $resdata, 'log');
                                }
                            }

                            unset($order_status);
                        }
                    }

                    unset($single);
                }
            }, 'update_time', 'asc');
    }

    /**
     * 支付宝代付处理 
     * @access protected
     * @return mixed
     */
    protected function alipayPaid()
    {

        // 设置至少间隔多少秒处理一次
        $notice_time = 15;

        // 代付公司配置
        $all_child_company = Db::name('payment_paid_company')
            ->where([])
            ->column('*', 'name');

        Db::name('payment_order_alipay_paid')
            ->where('status', '=', 1)
            ->chunk(10, function ($all) use ($notice_time, $all_child_company) {
                foreach ($all as $single) {

                    // 处理规则
                    if ($single['update_time'] + $notice_time < time()) {
                        sleep(1);
                        $redis = Cache::store('redis');

                        // 可能会在一秒中多次通知相同订单，用redis处理。
                        $order_notify_key = 'order_notify_' . $single['order_id'];
                        $order_notify = $redis->has($order_notify_key);
                        if ($order_notify) {
                            //payment_error_log(770007, $single, '多次通知:在一秒中多次通知相同订单');
                            unset($single);
                            continue;
                        } else {
                            $redis->set($order_notify_key, 1, 5);
                        }

                        // 订单状态
                        if (isset($order_status)) {
                            unset($order_status);
                        }

                        if (!isset($all_child_company[$single['child_company']])) {
                            payment_error_log(770008, $single);
                            continue;
                        }
                        $child_company_config = $all_child_company[$single['child_company']];
                        // 代付公司关闭定时自动查询
                        if ($child_company_config['auto_query'] == 0) {
                            continue;
                        }

                        $payment_company = $single['company'] . 'PaidQuery';
                        $order_id = $single['order_id'];
                        if (in_array($single['company'], ['abcdefg'])) {
                            $order_id = $single['other_order_id'];
                        }

                        // 实例化支付宝代付订单模型
                        $alipay_paid_obj = new \app\api\model\PaymentOrderAlipayPaid();
                        $resdata = $alipay_paid_obj->$payment_company($order_id, $child_company_config, $single, false, true);

                        $return_param = $resdata['return_param'];
                        $resarray = json_decode($return_param, true);

                        // 游易付代付
                        if ($single['company'] == 'youyifu') {
                            if (isset($resarray['state'])) {
                                // 成功
                                if ($resarray['state'] == 1) {
                                    $order_status = 2;
                                }
                                // 失败
                                if ($resarray['state'] == 2) {
                                    $order_status = 3;
                                }
                            }
                        }
                        // 薪航向代付
                        if ($single['company'] == 'xhx') {
                            if (isset($resarray['queryItems'][0]['orderStatus'])) {
                                // 成功
                                if ($resarray['queryItems'][0]['orderStatus'] == 2) {
                                    $order_status = 2;
                                }
                                // 失败
                                if ($resarray['queryItems'][0]['orderStatus'] == 3) {
                                    $order_status = 3;
                                }
                            }
                        }
                        // 灵时云代付
                        if ($single['company'] == 'lsy') {
                            if (isset($resarray['data']['planDetail'][0]['payState'])) {
                                // 成功
                                if ($resarray['data']['planDetail'][0]['payState'] == 3) {
                                    $order_status = 2;
                                }
                                // 失败
                                if ($resarray['data']['planDetail'][0]['payState'] == 4) {
                                    $order_status = 3;
                                }
                            }
                        }
                        // 支付宝官网代付
                        if ($single['company'] == 'zfb') {
                            if (isset($resarray['alipay_fund_trans_common_query_response']['status'])) {
                                // 成功
                                if ($resarray['alipay_fund_trans_common_query_response']['status'] == 'SUCCESS') {
                                    $order_status = 2;
                                }
                                // 失败
                                if ($resarray['alipay_fund_trans_common_query_response']['status'] == 'FAIL') {
                                    $order_status = 3;
                                }
                            }
                            if (isset($resarray['alipay_fund_trans_order_query_response']['status'])) {
                                // 成功
                                if ($resarray['alipay_fund_trans_order_query_response']['status'] == 'SUCCESS') {
                                    $order_status = 2;
                                }
                                // 失败
                                if ($resarray['alipay_fund_trans_order_query_response']['status'] == 'FAIL') {
                                    $order_status = 3;
                                }
                            }
                        }

                        if (isset($order_status)) {

                            try {
                                $update_data = Db::name('payment_order_alipay_paid')
                                    ->where(['order_id' => $single['order_id'], 'status' => 1])
                                    ->update(['status' => $order_status, 'update_time' => time()]);
                            } catch (\Exception $e) {
                                payment_error_log(770009, $single, $e->getMessage());
                                continue;
                            }

                            // 更新代付订单表状态失败
                            if (!$update_data) {
                                payment_error_log(770010, $single);
                                continue;
                            }

                            // 失败：代付金额退回
                            if ($order_status == 3) {
                                // 代付绿色通道
                                if ($single['paid_green_channel_status'] == 0) {
                                    try {
                                        Db::name('payment_cash')
                                            ->where(['merchant_id' => $single['merchant_id']])
                                            ->inc('paid_cash', $single['deduct_cash'])
                                            ->dec('paid_sum_cash', $single['deduct_cash'])
                                            ->dec('paid_count', 1)
                                            ->update(['update_time' => time()]);
                                    } catch (\Exception $e) {
                                        payment_error_log(770011, $single, $e->getMessage());
                                    }
                                }
                            }
                            // 成功：处理商户等配置
                            if ($order_status == 2) {

                                // 指定代付公司不执行
                                if (!in_array($single['company'], ['zfb'])) {

                                    $paid_cash = $single['cash'];
                                    $expire = strtotime(date('Y-m-d', strtotime('+1 day'))) - time();

                                    // 更新商户号今天已经代付的金额总数
                                    $merchant_day_alipay_paid_cash_sum = $single['merchant_id'] . '_day_alipay_paid_cash_sum';
                                    $now_merchant_day_alipay_paid_cash_sum = $redis->has($merchant_day_alipay_paid_cash_sum);
                                    if ($now_merchant_day_alipay_paid_cash_sum) {
                                        $redis->inc($merchant_day_alipay_paid_cash_sum, $paid_cash);
                                    } else {
                                        $redis->set($merchant_day_alipay_paid_cash_sum, $paid_cash, $expire);
                                    }

                                    // 更新代付公司中的子商户号今天已经代付的金额总数
                                    $children_day_paid_cash_sum = $single['child_company'] . '_day_paid_cash_sum';
                                    $now_children_day_paid_cash_sum = $redis->has($children_day_paid_cash_sum);
                                    if ($now_children_day_paid_cash_sum) {
                                        $redis->inc($children_day_paid_cash_sum, $paid_cash);
                                    } else {
                                        $redis->set($children_day_paid_cash_sum, $paid_cash, $expire);
                                    }

                                    // 通道每天最多代付成功次数
                                    $children_company_success_count = $single['child_company'] . '_success_count';
                                    $now_children_company_success_count = $redis->has($children_company_success_count);
                                    if ($now_children_company_success_count) {
                                        $redis->inc($children_company_success_count, 1);
                                    } else {
                                        $redis->set($children_company_success_count, 1, $expire);
                                    }

                                    // 通道每天最多代付用户成功次数（支付宝）
                                    if ($child_company_config['user_success_count'] != '0') {
                                        $children_company_user_success_count = $single['child_company'] . '_user_' . $single['account'];
                                        $now_children_company_user_success_count = $redis->has($children_company_user_success_count);
                                        if ($now_children_company_user_success_count) {
                                            $redis->inc($children_company_user_success_count, 1);
                                        } else {
                                            $redis->set($children_company_user_success_count, 1, $expire);
                                        }
                                    }
                                }
                            }

                            // 把代付信息通知给商户
                            $merchant_create_param = json_decode($single['create_param'], true);
                            // 商户开启通知
                            if ($merchant_create_param['notify_open'] == 1) {
                                $notify_url = $merchant_create_param['notify_url'];
                                $notify_data['code'] = 10000;                                         // 成功状态码
                                $notify_data['merchant_id'] = $single['merchant_id'];                 // 商户号
                                $notify_data['merchant_order_id'] = $single['merchant_order_id'];     // 商户订单号
                                $notify_data['order_id'] = $single['order_id'];                       // 平台订单号
                                $notify_data['app_id'] = $single['app_id'];                           // 应用id
                                $notify_data['cash'] = $single['cash'] / 100;                         // 代付现金    
                                $notify_data['deduct_cash'] = $single['deduct_cash'] / 100;           // 扣除金额    
                                $notify_data['mode'] = $single['mode'];                               // 代付方法：0自动，1手动
                                $notify_data['trade_type'] = $single['trade_type'];                   // 交易类型：比如充值、代付                                  
                                $notify_data['body'] = $single['body'];                               // 代付说明
                                $notify_data['time'] = time();                                        // 更新时间
                                $notify_data['extra'] = $merchant_create_param['extra'];              // 商户自定义备注
                                // 订单状态：1:处理中 2:成功 3:失败 4:异常
                                $notify_data['status'] = $order_status;
                                $notify_data['sign'] = md5('merchant_id=' . $notify_data['merchant_id'] . '&merchant_order_id=' . $notify_data['merchant_order_id'] . '&order_id=' . $notify_data['order_id'] . '&cash=' . $notify_data['cash'] . '&status=' . $notify_data['status'] . '&time=' . $notify_data['time'] . '&key=' . $merchant_create_param['key']);

                                $resdata = go_curl($notify_url, $notify_data, 'get', 12);
                                if (stripos($resdata, 'success') === false) {
                                    // 通知失败,准备多次通知
                                    $url_param = http_build_query($notify_data);
                                    $url = strpos($notify_url, '?') !== false ? $notify_url . '&' . $url_param : $notify_url . '?' . $url_param;

                                    $notify_array = [
                                        'order_id' => $single['order_id'],
                                        'merchant_id' => $single['merchant_id'],
                                        'merchant_order_id' => $single['merchant_order_id'],
                                        'other_order_id' => $single['other_order_id'],
                                        'app_id' => $single['app_id'],
                                        'cash' => $single['cash'],
                                        'type' => 0,
                                        'trade_type' => $single['trade_type'],
                                        'status' => 0,
                                        'manual' => 0,
                                        'count' => 0,
                                        'create_time' => $single['create_time'],
                                        'update_time' => time(),
                                        'url' => $url,
                                        'remark' => substr($resdata, 0, 60000),
                                    ];
                                    // 插入多次通知数据库
                                    try {
                                        Db::name('payment_order_notify')->insert($notify_array);
                                    } catch (\Exception $e) {
                                        payment_error_log(770012, $notify_array, $e->getMessage());
                                    }

                                    Log::record("代付通知商户号{$single['merchant_id']}失败记录：" . $single['order_id'] . '——' . '0', 'log');
                                    Log::record('代付通知URL参数：' . $url, 'log');
                                    Log::record('代付通知返回内容：' . $resdata, 'log');
                                }
                            }

                            unset($order_status);
                        }
                    }

                    unset($single);
                }
            }, 'update_time', 'asc');
    }

    /**
     * 银行卡代付失败处理 
     * @access protected
     * @param  array  $single                代付数据
     * @param  array  $child_company_config  代付配置
     * @return mixed
     */
    protected function cardPaidFailHandle($single = [], $child_company_config = [])
    {
        try {
            $merchant_param = json_decode($single['create_param'], true);

            // 发送给第三方支付公司参数（代付）
            $param['order_id'] = $single['order_id'];                      // 平台订单号
            $param['cash'] = $single['cash'] / 100;                        // 金额
            $param['account_type'] = $single['account_type'];              // 账户类型
            $param['body'] = '转账';                                       // 付款说明
            $param['bank_code'] = strtoupper($single['bank_code']);        // 银行编号
            $param['bank_card'] = $single['bank_card'];                    // 银行卡号
            $param['name'] = $single['name'];                              // 收款方用户名
            $param['id_card'] = $merchant_param['id_card'];                // 身份证
            $param['now_time'] = time();                                   // 现在时间
            $param['other_param'] = $single;                               // 其他参数

            $company_paid_type = 'Paid';
            if (in_array($single['company'], ['lianlian'])) {
                $company_paid_type = 'PaidConfirm';
            }
            $payment_company = $single['company'] . $company_paid_type;

            // 实例化第三方代付订单模型
            $card_paid_obj = new \app\api\model\PaymentOrderPaid();
            $resarray = $card_paid_obj->$payment_company($param, $child_company_config);

            // 状态：1:处理中 2:成功 3:失败 4:异常 
            $update['status'] = $resarray['code'] == 200 ? 1 : 3;
            $update['other_order_id'] = isset($resarray['other_order_id']) ? $resarray['other_order_id'] : '';
            $update['return_param'] = isset($resarray['return_param']) ? substr($resarray['return_param'], 0, 60000) : '';
            $update['update_time'] = time();

            try {
                Db::name('payment_order_paid')->where(['order_id' => $single['order_id']])->update($update);
            } catch (\Exception $e) {
                payment_error_log(770014, $single, $e->getMessage());
            }

            // 失败：代付金额退回
            if ($update['status'] == 3) {
                // 代付绿色通道
                if ($single['paid_green_channel_status'] == 0) {
                    try {
                        Db::name('payment_cash')
                            ->where(['merchant_id' => $single['merchant_id']])
                            ->inc('paid_cash', $single['deduct_cash'])
                            ->dec('paid_sum_cash', $single['deduct_cash'])
                            ->dec('paid_count', 1)
                            ->update(['update_time' => time()]);
                    } catch (\Exception $e) {
                        payment_error_log(770015, $single, $e->getMessage());
                    }
                }

                // 把代付信息通知给商户
                $merchant_create_param = json_decode($single['create_param'], true);
                // 商户开启通知
                if ($merchant_create_param['notify_open'] == 1) {
                    $notify_url = $merchant_create_param['notify_url'];
                    $notify_data['code'] = 10000;                                         // 成功状态码
                    $notify_data['merchant_id'] = $single['merchant_id'];                 // 商户号
                    $notify_data['merchant_order_id'] = $single['merchant_order_id'];     // 商户订单号
                    $notify_data['order_id'] = $single['order_id'];                       // 平台订单号
                    $notify_data['app_id'] = $single['app_id'];                           // 应用id
                    $notify_data['cash'] = $single['cash'] / 100;                         // 代付现金    
                    $notify_data['deduct_cash'] = $single['deduct_cash'] / 100;           // 扣除金额    
                    $notify_data['mode'] = $single['mode'];                               // 代付方法：0自动，1手动
                    $notify_data['trade_type'] = $single['trade_type'];                   // 交易类型：比如充值、代付                                  
                    $notify_data['body'] = $single['body'];                               // 代付说明
                    $notify_data['time'] = time();                                        // 更新时间
                    $notify_data['extra'] = $merchant_create_param['extra'];              // 商户自定义备注
                    // 订单状态：1:处理中 2:成功 3:失败 4:异常
                    $notify_data['status'] = $update['status'];
                    $notify_data['sign'] = md5('merchant_id=' . $notify_data['merchant_id'] . '&merchant_order_id=' . $notify_data['merchant_order_id'] . '&order_id=' . $notify_data['order_id'] . '&cash=' . $notify_data['cash'] . '&status=' . $notify_data['status'] . '&time=' . $notify_data['time'] . '&key=' . $merchant_create_param['key']);

                    $resdata = go_curl($notify_url, $notify_data, 'get', 12);
                    if (stripos($resdata, 'success') === false) {
                        // 通知失败,准备多次通知
                        $url_param = http_build_query($notify_data);
                        $url = strpos($notify_url, '?') !== false ? $notify_url . '&' . $url_param : $notify_url . '?' . $url_param;

                        $notify_array = [
                            'order_id' => $single['order_id'],
                            'merchant_id' => $single['merchant_id'],
                            'merchant_order_id' => $single['merchant_order_id'],
                            'other_order_id' => $single['other_order_id'],
                            'app_id' => $single['app_id'],
                            'cash' => $single['cash'],
                            'type' => 0,
                            'trade_type' => $single['trade_type'],
                            'status' => 0,
                            'manual' => 0,
                            'count' => 0,
                            'create_time' => $single['create_time'],
                            'update_time' => time(),
                            'url' => $url,
                            'remark' => substr($resdata, 0, 60000),
                        ];
                        // 插入多次通知数据库
                        try {
                            Db::name('payment_order_notify')->insert($notify_array);
                        } catch (\Exception $e) {
                            payment_error_log(770016, $notify_array, $e->getMessage());
                        }

                        Log::record("代付通知商户号{$single['merchant_id']}失败记录：" . $single['order_id'] . '——' . '0', 'log');
                        Log::record('代付通知URL参数：' . $url, 'log');
                        Log::record('代付通知返回内容：' . $resdata, 'log');
                    }
                }
            }

            Log::record("平台订单号：{$single['order_id']}：{$single['company']}代付重新提交返回结果：{$update['return_param']}", 'error');

            return $update['status'];
        } catch (\Exception $e) {
            payment_error_log(770013, $e->getMessage());
            return ['code' => 999, 'msg' => '404'];
        }
    }
}
